package com.avic.rong.activity.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.activity.mine.BindPhoneActivity;
import com.avic.rong.api.SendCodeApi;
import com.avic.rong.api.login_register.BindWxApi;
import com.avic.rong.api.login_register.WxLoginApi;
import com.avic.rong.bean.MinePageEvent;
import com.avic.rong.bean.login_register.LoginPhoneBean;
import com.avic.rong.bean.login_register.WxLoginBean;
import com.avic.rong.utils.NetWorkUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.RegexUtils;
import com.avic.rong.utils.StatusBarUtil;
import com.avic.rong.utils.StringUtils;
import com.avic.rong.utils.TimeCount;
import com.avic.rong.utils.ToastTools;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.luck.picture.lib.dialog.CustomDialog;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;

//登陆注册-微信登陆
public class WxLoginActivity extends RxAppCompatActivity implements BGASwipeBackHelper.Delegate {

    @BindView(R.id.img_return)
    ImageView img_return;
    @BindView(R.id.type_pwd_phone)
    EditText type_pwd_phone;
    @BindView(R.id.type_code)
    EditText type_code;
    @BindView(R.id.tv_send)
    TextView tv_send;
    @BindView(R.id.btn_login)
    Button btn_login;
    @BindView(R.id.tv_user_protocol)
    TextView tv_user_protocol;
    @BindView(R.id.tv_not_findyzma)
    TextView tv_not_findyzma;
    @BindView(R.id.cb_user)
    CheckBox cbUser;
    @BindView(R.id.iv_user)
    ImageView iv_user;
    @BindView(R.id.wx_user)
    TextView wx_user;
    private String json;
    private String uid;
    private WxLoginApi wxLoginApi;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private BGASwipeBackHelper mSwipeBackHelper;
    private InputMethodManager imm;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wx_login);

        ButterKnife.bind(this);

        //设置状态栏颜色
        StatusBarUtil.setStatusBarColor(this,getResources().getColor(R.color.color_loginbg));
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);


        sharedPreferencesUtil = SharedPreferencesUtil.getInstance();


        if (getIntent()!=null) {
            json = getIntent().getStringExtra("json");
            WxLoginBean bean = (WxLoginBean) getIntent().getSerializableExtra("wxBean");
            String iconurl = bean.getIconurl();
            String name = bean.getName();
            uid = bean.getUid();
            Glide.with(this).applyDefaultRequestOptions(RequestOptions.circleCropTransform()).load(iconurl).into(iv_user);
            wx_user.setText(name+"，您好！");
        }
        Log.e("wcx", "onCreate: "+json );
        type_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() >= 6) {
                    btn_login.setBackgroundResource(R.mipmap.bg_btlogin);
                    btn_login.setTextColor(getResources().getColor(R.color.white));
                    btn_login.setEnabled(true);
                } else {
                    btn_login.setBackgroundResource(R.mipmap.grey_login);
                    btn_login.setTextColor(getResources().getColor(R.color.black_text));
                    btn_login.setEnabled(false);
                }
            }
        });

        initSwipeBackFinish();
        overridePendingTransition(R.anim.slide_in_right, R.anim.keep);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (this.getCurrentFocus() != null) {
                if (this.getCurrentFocus().getWindowToken() != null) {
                    imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }

    public static Intent queryIntent(Context context) {
        Intent intent = new Intent(context, WxLoginActivity.class);
        return intent;
    }

    public static Intent queryIntent(Context context, String json) {
        Intent intent = new Intent(context, WxLoginActivity.class);
        intent.putExtra("json", json);
        return intent;
    }

    @OnClick({R.id.img_return, R.id.tv_user_protocol, R.id.tv_send, R.id.btn_login, R.id.tv_not_findyzma})
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.tv_user_protocol:
                startActivity(UserProtocolActivity.queryIntent(WxLoginActivity.this));
                break;
            case R.id.img_return:
                finish();
                break;
            case R.id.tv_send:
                sendCode();
                break;
            case R.id.btn_login:
                boolean checked = cbUser.isChecked();
                if (checked) {
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                    bindWx();
                }else {
                    ToastTools.showPublicToast("请先同意用户协议");
                }

                break;
            case R.id.tv_not_findyzma:
                startActivity(NotGetCodeActivity.queryIntent(this));
                break;
        }
    }

    private void bindWx() {
        String phone = type_pwd_phone.getText().toString().trim();
        String code = type_code.getText().toString().trim();

        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            ToastTools.showPublicToast("手机号或验证码不能为空");
            return;
        }
        if (!RegexUtils.isMobileExact(phone)) {
            ToastTools.showPublicToast("手机号格式不正确");
            return;
        }

        BindWxApi bindWxApi = new BindWxApi(this, bindWxListener);
        bindWxApi.setArguments(phone, code, json);
        bindWxApi.setRetryCount(1);//重新请求
        bindWxApi.setCancel(false);
        bindWxApi.setShowProgress(true);
        HttpManager.getInstance().doHttpDeal(bindWxApi);
    }

    HttpOnNextListener<BaseResultEntity> bindWxListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onError(Throwable e) {
            String networkState = NetWorkUtils.getNetworkState(WxLoginActivity.this);
           ToastTools.showPublicToast(networkState);
        }
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                LoginPhoneBean data = (LoginPhoneBean) baseResultEntity.getData();
                if (data.isBindingMobile()) {
                    wxLoginApi = new WxLoginApi(WxLoginActivity.this, wxLoginListener);
                    wxLoginApi.setArgment(uid);
                    wxLoginApi.setShowProgress(true);
                    wxLoginApi.setCancel(false);
                    HttpManager.getInstance().doHttpDeal(wxLoginApi);
                } else {
                    showDialog();
                }
            }else {
                ToastTools.showPublicToast(baseResultEntity.getMsg());
            }
        }
    };


    //    微信登陆
    HttpOnNextListener<BaseResultEntity> wxLoginListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                LoginPhoneBean data = (LoginPhoneBean) baseResultEntity.getData();

                if (data.isBindingMobile()) {
                    sharedPreferencesUtil.setLoginState(true);//登录状态
                    sharedPreferencesUtil.setLogintoken(data.getToken());
                    sharedPreferencesUtil.setUserId(data.getUserId()+"");

                    Intent intent = new Intent("android.intent.action.CART_BROADCAST");
                    intent.putExtra("data","refresh");
                    LocalBroadcastManager.getInstance(WxLoginActivity.this).sendBroadcast(intent);
                    sendBroadcast(intent);
                    EventBus.getDefault().postSticky(new MinePageEvent());
                    Intent intent1 = MainActivity.queryIntent(WxLoginActivity.this);
                    intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent1);
                } else{
                    showDialog();
                }
            }else if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_BIND_PHONE_1013)){
                showDialog();
            }
        }
        @Override
        public void onError(Throwable e) {
            String networkState = NetWorkUtils.getNetworkState(WxLoginActivity.this);
           ToastTools.showPublicToast(networkState);
        }
    };


    private void showDialog() {
        CustomDialog customDialog = new CustomDialog(this, R.layout.bindphone_dialog);
        customDialog.show();
        customDialog.setCanceledOnTouchOutside(false);
        customDialog.setCancelable(false);

        customDialog.findViewById(R.id.tv_bind).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(BindPhoneActivity.queryIntent(WxLoginActivity.this));
            }
        });
    }

    private void sendCode() {

        String phone = type_pwd_phone.getText().toString().trim();
        if (StringUtils.isEmpty(phone)) {
            ToastTools.showPublicToast("手机号不能为空");
            return;
        }
        if (!RegexUtils.isMobileExact(phone)) {
            ToastTools.showPublicToast("手机号格式不正确");
            return;
        }

        SendCodeApi sendCodeApi = new SendCodeApi(this, sendCodeBeanListener);

        sendCodeApi.setArguments(phone, 7, SharedPreferencesUtil.SIGN);
        sendCodeApi.setCancel(false);
        sendCodeApi.setShowProgress(true);
        HttpManager.getInstance().doHttpDeal(sendCodeApi);

    }

    HttpOnNextListener<BaseResultEntity> sendCodeBeanListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                timeOut();
            }else {
                ToastTools.showPublicToast(baseResultEntity.getMsg());
            }
        }
    };

    private void timeOut() {
        TimeCount timeCount = new TimeCount(60000, 1000, tv_send,false);
        timeCount.start();
    }

    /**
     * 初始化滑动返回。在 super.onCreate(savedInstanceState) 之前调用该方法
     */
    private void initSwipeBackFinish() {
        mSwipeBackHelper = new BGASwipeBackHelper(this, this);

        // 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackHelper.init 来初始化滑动返回」
        // 下面几项可以不配置，这里只是为了讲述接口用法。

        // 设置滑动返回是否可用。默认值为 true
        mSwipeBackHelper.setSwipeBackEnable(true);
        // 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
        mSwipeBackHelper.setIsOnlyTrackingLeftEdge(true);
        // 设置是否是微信滑动返回样式。默认值为 true
        mSwipeBackHelper.setIsWeChatStyle(true);
        // 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
        mSwipeBackHelper.setShadowResId(R.drawable.bga_sbl_shadow);
        // 设置是否显示滑动返回的阴影效果。默认值为 true
        mSwipeBackHelper.setIsNeedShowShadow(true);
        // 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
        mSwipeBackHelper.setIsShadowAlphaGradient(true);
        // 设置触发释放后自动滑动返回的阈值，默认值为 0.3f
        mSwipeBackHelper.setSwipeBackThreshold(0.3f);
        // 设置底部导航条是否悬浮在内容上，默认值为 false
        mSwipeBackHelper.setIsNavigationBarOverlap(false);
    }

    /**
     * 是否支持滑动返回。这里在父类中默认返回 true 来支持滑动返回，如果某个界面不想支持滑动返回则重写该方法返回 false 即可
     *
     * @return
     */
    @Override
    public boolean isSupportSwipeBack() {
        return false;
    }

    /**
     * 正在滑动返回
     *
     * @param slideOffset 从 0 到 1
     */
    @Override
    public void onSwipeBackLayoutSlide(float slideOffset) {
    }

    /**
     * 没达到滑动返回的阈值，取消滑动返回动作，回到默认状态
     */
    @Override
    public void onSwipeBackLayoutCancel() {
    }

    /**
     * 滑动返回执行完毕，销毁当前 Activity
     */
    @Override
    public void onSwipeBackLayoutExecuted() {
        mSwipeBackHelper.swipeBackward();
    }

    @Override
    public void onBackPressed() {
        // 正在滑动返回的时候取消返回按钮事件

        if (mSwipeBackHelper.isSliding()) {
            return;
        }
        mSwipeBackHelper.backward();
        overridePendingTransition(R.anim.keep, R.anim.out_from_right);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.keep, R.anim.out_from_right);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
